<?php

namespace App\Http\Admin\Services\Order;

use App\Exceptions\InvalidRequestException;

use App\Http\Models\OrderWechat;
use App\Http\Services\BaseOrderService;
use App\Lib\PHPExcel\ExcelHandle;
use Illuminate\Support\Facades\DB;


class OrderWeChatService extends BaseOrderService
{
    public function orderWechatImport(){
        $arr = ExcelHandle::read();

        if (count($arr) == 0) {
            throw new InvalidRequestException('数据不能为空');
        }
        $i = 0;
        foreach ($arr as $item){
            if(!empty($item['A'])){

                $order_id = $item['A'];
                $it = [
                    'order_id' => $item['A'],
                    'liver' => $item['B'],
                    'customer' => $item['C'],
                    'phone' => $item['D'],
                    'manu_name' => $item['E'],
                    'product_name' => $item['F'],
                    'price' => !empty($item['G']) ? $item['G'] : 0,
                    'cost_price' => !empty($item['H']) ? $item['H'] : 0,
                    'pay_type' => $item['I'],
                    'summary' => $item['J'],
                    'expend' => !empty($item['K']) ? $item['K'] : 0,
                    'surplus' => !empty($item['L']) ? $item['L'] : 0,
                    'remark' => $item['M'],
                    'customer_service' => $item['N'],
                    'create_time' => !empty($item['O']) ? $item['O']:null,
                ];

                $flag = OrderWechat::where('order_id',$order_id)->exists();
                if($flag){
                    OrderWechat::where('order_id',$order_id)->update($it);
                }else{
                    OrderWechat::create($it);
                }
                $i++;
            }
        }
        return $i;
    }

    public function list($conditions = []){
        $query = OrderWechat::query();
        $query = $this->withCondition($conditions,$query);
        $query_sum = clone ($query);
        $list = $query->orderBy('create_time','desc')->paginate(50);
        //算综合
        $raw = DB::raw('sum(price) as total_price,sum(cost_price) as total_cost_price,sum(expend) as total_expend');
        $data = $query_sum->select($raw)->first();
        return [
          'list' =>  $list,
          'data' =>  $data
        ];
    }

    public function withCondition($conditions = [],$query){

        if(!empty($conditions['order_id'])){
            $query->where('order_id',$conditions['order_id']);
        }
        if(!empty($conditions['phone'])){
            $query->where('phone',$conditions['phone']);
        }
        if(!empty($conditions['start_time'])){
            $query->where('create_time','>=',$conditions['start_time']);
        }

        if(!empty($conditions['end_time'])){
            $query->where('create_time','<=',$conditions['end_time']);
        }

        return $query;

    }

}
